﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Data;
//using VAdvantage.LocalStorageManager;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Utility;

namespace VAdvantage.DataBase
{
    public class DataStorage
    {
        //public static DataStorage _data = null;

        //private Dictionary<String, DataTable> dicTables = null;

        //private Dictionary<String, XElement> dicElements = null;

        //private DataStorage()
        //{
        //    dicTables = new Dictionary<string, DataTable>(8);
        //    dicElements = new Dictionary<string,XElement>(8);
        //}

        //public static DataStorage Get()
        //{
        //    if(_data == null)
        //        _data = new DataStorage();
        //    return _data;
        //}

        //public static void Add(string key, DataTable val)
        //{
        //    DataStorage.Get().dicTables[key] =  val;
        //}

        //internal static void AddXElement(string key, XElement xElement)
        //{
        //    DataStorage.Get().dicElements[key] =  xElement;
        //}

        //public static DataTable GetWindow()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[ StorageManager.WINDOW_V];
        //}

        //public static DataTable GetTab()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.TAB_V];
        //}

        //public static DataTable GetField()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.FIELD_V];
        //}

        //public static DataTable GetTable()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.TABLE_V];
        //}

        //public static DataTable GetColumn()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.COLUMN_V];
        //}

        ////public static DataTable GetRefTable()
        ////{
        ////    if (_data == null)
        ////        return null;
        ////    return _data.dicTables[StorageManager.REF_TABLE_V];
        ////}


        //public static DataTable GetLookupTable()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.LOOKUP_Table];
        //}

        //public static DataTable GetLookupTranslated()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.LOOKUP_ISTRANSLATED];
        //}

        //public static DataTable GetLookupDiplayCol()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicTables[StorageManager.LOOKUP_DISPLAYCOL];
        //}

        //public static void Dispose()
        //{
        //    if (_data != null)
        //    {
        //        _data.dicTables.Clear();
        //        _data = null;
        //    }
        //}

        //public static XElement GetWindow()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.WINDOW_V];
        //}

        //public static XElement GetTab()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.TAB_V];
        //}

        //public static XElement GetField()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.FIELD_V];
        //}

        //public static XElement GetTable()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.TABLE_V];
        //}

        ////public static DataTable GetColumn()
        ////{
        ////    if (_data == null)
        ////        return null;
        ////    return _data.dicTables[StorageManager.COLUMN_V];
        ////}

        ////public static DataTable GetRefTable()
        ////{
        ////    if (_data == null)
        ////        return null;
        ////    return _data.dicTables[StorageManager.REF_TABLE_V];
        ////}

        //public static XElement GetLookupTable()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.LOOKUP_Table];
        //}

        //public static XElement GetLookupTranslated()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.LOOKUP_ISTRANSLATED];
        //}

        //public static XElement GetLookupDiplayCol()
        //{
        //    if (_data == null)
        //        return null;
        //    return _data.dicElements[StorageManager.LOOKUP_DISPLAYCOL];
        //}

        private static CCache<string, XElement> _windowCache = new CCache<string, XElement>("WindowCache", 5);

        private static CCache<string, XElement> _tabFieldCache = new CCache<string, XElement>("TabCache", 5);

        private static CCache<string,XElement> _lookupInfoCache = new CCache<string,XElement>("LookupCache", 1);

        private static void GetWTF(int AD_Window_ID,int AD_Role_ID ,bool isBaseLanguage,string lang)
        {

            bool loading = false;
            var client = AEnv.GetDataServiceBasicClient();
            client.GetWindowTabsFieldsCompleted += (s, e) =>
                {
                    if (e.error == null)
                    {
                        _windowCache.Add(AD_Window_ID + "|" + lang, XElement.Parse(e.Result));
                    }
                    else
                    {
                        //log
                    }
                    loading = false;
                };
            client.GetWindowTabsFieldsAsync(AD_Window_ID.ToString(),AD_Role_ID.ToString(),isBaseLanguage,lang);
            client.CloseAsync();
            loading = true;
            while (loading)
                System.Threading.Thread.Sleep(1);
        }

        //Window Tab And Fields
        internal static XElement GetWTFCache( int AD_Window_ID,int AD_Role_ID)
        {
            bool isBaseLanguage = Utility.Envs.IsBaseLanguage(Envs.GetCtx(), "AD_Window");
            string lang = Utility.Envs.GetAD_Language(Envs.GetCtx());
            string key = AD_Window_ID + "|" + lang;

            if (!_windowCache.ContainsKey(key))
            {
                Logging.VLogger.Get().Info("from server <===> " + AD_Window_ID); 
                GetWTF(AD_Window_ID, AD_Role_ID,isBaseLanguage,lang);
            }
            return _windowCache[key];
        }

    //    internal static void GetTabFields(int AD_Window_ID, int AD_UserDef_Win_ID, bool isBaseLanguage, string lang)
    //    {

    //        String sql = "SELECT * FROM AD_Tab_v WHERE AD_Window_ID="+AD_Window_ID;
    //        if (!isBaseLanguage)
    //            sql = "SELECT * FROM AD_Tab_vt WHERE AD_Window_ID="+AD_Window_ID
    //                + " AND AD_Language='" + lang + "'";
    //        if (AD_UserDef_Win_ID != 0)
    //            sql += " AND AD_UserDef_Win_ID=" + AD_UserDef_Win_ID;
    //        sql += " ORDER BY SeqNo";


    //        String sqlFieldWhere = "SELECT AD_Tab_ID FROM AD_Tab_v WHERE AD_Window_ID=" + AD_Window_ID;
    //        if (!isBaseLanguage)
    //            sqlFieldWhere = "SELECT AD_Tab_ID FROM AD_Tab_vt WHERE AD_Window_ID=" + AD_Window_ID
    //                + " AND AD_Language='" + lang + "'";
    //        if (AD_UserDef_Win_ID != 0)
    //            sqlFieldWhere += " AND AD_UserDef_Win_ID=" + AD_UserDef_Win_ID;
    //        //sqlFieldWhere += " ORDER BY SeqNo";


    //        String sqlField = "SELECT * FROM AD_Field_v WHERE AD_Tab_ID IN ( "+sqlFieldWhere+ " )";
    //        if (!isBaseLanguage)
    //            sqlField = "SELECT * FROM AD_Field_vt WHERE AD_Tab_ID IN ( " + sqlFieldWhere + " )"
    //                + " AND AD_Language='" + lang + "'";
    //        if (AD_UserDef_Win_ID != 0)
    //            sqlField += " AND AD_UserDef_Win_ID=" + AD_UserDef_Win_ID;
    //        sqlField += " ORDER BY IsDisplayed DESC, SeqNo";

    //        bool loading = false;
    //        var client = AEnv.GetDataServiceBasicClient();
    //        client.GetDataTablesCompleted += (s, e) =>
    //        {
    //            _tabFieldCache.Add(AD_Window_ID + "|" + lang, XElement.Parse(e.Result));
    //            loading = false;
    //        };
    //        client.GetDataTablesAsync(sql + "/" + sqlField);
    //        client.CloseAsync();
    //        loading = true;
    //        while (loading)
    //            System.Threading.Thread.Sleep(1);
    //    }

    //    internal static XElement GetTabFieldFromCache(int AD_Window_ID, int AD_UserDef_Win_ID)
    //    {
    //        bool isBaseLanguage = Utility.Envs.IsBaseLanguage(Envs.GetCtx(), "AD_Window");
    //        string lang = Utility.Envs.GetAD_Language(Envs.GetCtx());
    //        string key = AD_Window_ID + "|" + lang;

    //        if (!_tabFieldCache.ContainsKey(key))
    //        {
    //            GetTabFields(AD_Window_ID, AD_UserDef_Win_ID, isBaseLanguage, lang);
    //        }
    //        return  _tabFieldCache[key];
    //    }


        private static void FillLookupInfoCache()
        {
            string sqlTable = "SELECT AD_Table_ID as AD_TABLE_ID,TableName as TABLENAME, AD_Window_ID as AD_WINDOW_ID,PO_Window_ID as PO_WINDOW_ID,IsActive as ISACTIVE From AD_Table";

            string sqlDisplayCol = "SELECT c.ColumnName as ColumnName,c.IsTranslated as IsTranslated,c.AD_Reference_ID as AD_Reference_ID,"
                    + "c.AD_Reference_Value_ID as AD_Reference_Value_ID,t.AD_Window_ID as AD_Window_ID,t.PO_Window_ID as PO_Window_ID,t.TableName as TableName"
                    + " FROM AD_Table t, " 
                    + " AD_Column c "
                    +"  WHERE t.AD_Table_ID=c.AD_Table_ID "
                    + " AND c.IsIdentifier='Y' "
                    + " ORDER BY c.SeqNo";

            string sqlRefTable = "SELECT t.TableName as TableName,ck.ColumnName AS KeyColumn,"				//	1..2
                + "cd.ColumnName AS DisplayColumn,rt.IsValueDisplayed as IsValueDisplayed ,cd.IsTranslated as IsTranslated,"	//	3..5
                + "rt.WhereClause as WhereClause,rt.OrderByClause as OrderByClause,t.AD_Window_ID as AD_Window_ID,t.PO_Window_ID as PO_Window_ID, "		//	6..9
                + "t.AD_Table_ID as AD_Table_ID, rt.AD_Reference_ID as AD_Reference_ID "  // rt.IsDisplayIdentifiers "								//	10..11
                + " FROM AD_Ref_Table rt"
                + " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID)"
                + " INNER JOIN AD_Column ck ON (rt.Column_Key_ID=ck.AD_Column_ID)"
                + " INNER JOIN AD_Column cd ON (rt.Column_Display_ID=cd.AD_Column_ID) "
                + " AND rt.IsActive='Y' AND t.IsActive='Y'";

            string sqlTranslated = @"SELECT count(*) as count,t.TableName as TableName
                FROM AD_Table t, AD_Column c WHERE t.AD_Table_ID=c.AD_Table_ID 
                 AND c.IsIdentifier='Y' 
                AND c.IsTranslated = 'Y'
                GROUP BY TableName";


            bool loading = false;
                    var client = AEnv.GetDataServiceBasicClient();
                    client.GetDataTablesCompleted += (s, e) =>
                    {
                       //XElement m =  XElement.Parse(e.Result);
                       //XElement m1 = XElement.Load(
                        _lookupInfoCache.Add("LookupInfo", XElement.Parse(e.Result));
                        loading = false;
                    };
                    client.GetDataTablesAsync(sqlTable + "/" + sqlDisplayCol + "/" + sqlRefTable + "/" + sqlTranslated);
                    client.CloseAsync();
            //        loading = true;
            //        while (loading)
            //            System.Threading.Thread.Sleep(1);


        }


        internal static XElement GetLookupInfoCache()
        {

            if (!_lookupInfoCache.ContainsKey("LookupInfo"))
            {
                FillLookupInfoCache();
            }
            return _lookupInfoCache["LookupInfo"];
        }

        internal static void FillWorkFlowCache()
        {
            new System.Threading.Thread(new System.Threading.ThreadStart(delegate
                                {
                                    WF.MWorkflow.GetDocValue(Envs.GetCtx(), 0, 0);
                                })).Start();
        }
    }
}
